const Router = require('koa-router');
const router = new Router();
const Detail = require('../models/detail');
const retry = require('async-retry');

const cache = new Map(); // 可能会存在内存泄漏问题，需要定期清理（但我每天重启了）

router.get('/api/detail/:oid', async (ctx) => {
    const oid = ctx.params.oid;

    if (cache.has(oid)) {
        ctx.body = cache.get(oid);
        console.log('-------------')
        return;
    }

    try {
        const data = await retry(
            async (bail) => {
                try {
                    return await Detail.findOne({
                        where: { oid },
                        raw: true
                    });
                } catch (error) {
                    if (error.name === 'SequelizeDatabaseError') {
                        throw error; // 重试
                    } else {
                        bail(error); // 不重试
                    }
                }
            },
            {
                retries: 3, // 最大重试次数
                minTimeout: 1000 // 最小重试间隔
            }
        );

        if (data) {
            cache.set(oid, data);
            ctx.body = data;
        } else {
            ctx.status = 404;
        }
    } catch (error) {
        ctx.status = 500;
        ctx.body = { message: '服务器繁忙，请稍后再试' };
    }
});

// 创建订单详情
router.post('/api/new-detail', async (ctx, next) => {
    const { oid, data } = ctx.request.body;
    try {
        const user = await Detail.create({ oid, data: JSON.stringify(data) });
        ctx.body = user;
    } catch (error) {
        console.error('创建订单详情失败：', error);
        ctx.body = {
            message: '创建订单详情失败'
        };
    }
});

// 修改订单详情
router.put('/api/update-detail/:oid', async (ctx) => {
    const { oid } = ctx.params;
    const data = ctx.request.body;
    const updateData = { 
        oid,
        data: JSON.stringify(data)
    };

    try {
        const [affectedCount] = await Detail.update(
            updateData,
            { where: { oid } }
        );

        if (affectedCount > 0) {
            // 更新缓存
            cache.set(oid, { oid, data });
            ctx.status = 200;
            ctx.body = {
                success: true,
                message: '订单详情更新成功'
            };
        } else {
            // 先查询是否存在该记录
            const exists = await Detail.findOne({ where: { oid } });
            ctx.status = 404;
            ctx.body = {
                success: false,
                message: exists ? '数据无变化' : '未找到指定订单详情',
                oidExists: !!exists
            };
        }
    } catch (error) {
        console.error('修改订单详情失败：', error);
        ctx.status = 500;
        ctx.body = {
            success: false,
            message: '修改订单详情失败',
            error: error.message
        };
    }
});

module.exports = app => {
    app.use(router.routes())
        .use(router.allowedMethods())
}